﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Veteran_cms.Models;
using THS.HtmlHelpers;
using System.IO;
namespace Veteran_cms.Controllers
{
    [HandleError]
    public class ManageMultimediaSetController : BaseController
    {
        const int PageSize = 6;
        readonly Veterandb _ctx = new Veterandb();
        //
        // GET: /ManageAbout/
        public ActionResult IndexMultimediaSet(int page = 1)
        {
            var model = new HomeAdminListViewModel();
            IList<multimedia_set> multimedias = _ctx.multimedia_set.OrderBy(p => p.set_id).ToList();
            model.MultimediaSets = multimedias.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            model.MultimediaSetPageInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = multimedias.Count() };
            return View(model);

        }
        public ActionResult Paging(int page = 1)
        {
            var model = new HomeAdminListViewModel();
            IList<multimedia_set> multimedias = _ctx.multimedia_set.ToList();
            model.MultimediaSets = multimedias.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            model.MultimediaSetPageInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = multimedias.Count() };
            return PartialView("UCMultimediaSetList", model);

        }

        public ActionResult Details(int id)
        {
            // TODO: Add update logic here
            //if (!IsAuthenticateAdmin())
            //    return RedirectToAction("LogOn", "DashBoard");
            InitCategory(0);
            var file = _ctx.multimedia_set.SingleOrDefault(f => f.set_id == id);
            if (file != null)
                return View(file);
            else
            {
                file = new Models.multimedia_set();
                return View(file);
            }
            //return trang thông báo lỗi
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Details(int id, HttpPostedFileBase uploadFile)
        {
            try
            {
                // TODO: Add update logic here
                //if (!IsAuthenticateAdmin())
                //    return RedirectToAction("LogOn", "DashBoard");
                var file = _ctx.multimedia_set.SingleOrDefault(p => p.set_id == id);
                var changeImage = false;
                var oldImage = string.Empty;
                var oldThumbImage = string.Empty;
                if (uploadFile != null)
                {
                    if (file != null && file.set_id > 0)
                    {
                        oldImage = file.image_large;
                        oldThumbImage = file.image_thumbnail;

                        var fileName = Path.GetFileName(uploadFile.FileName);
                        var sFileName = GenerateFileNameByNo(Request, Utilities.VirtualPath, fileName, DateTime.Now.ToString("yyyyMMddhhmmss"));
                        var filePath = Path.Combine(Request.MapPath(Utilities.VirtualPath), sFileName);
                        var fileThumbPath = Path.Combine(Request.MapPath(Utilities.VirtualPath + "Thumbs/"), sFileName);
                        ResizeImage(uploadFile.InputStream, fileThumbPath, 99, 99, true);
                        ResizeImage(uploadFile.InputStream, filePath, 400, 300, true);
                        file.image_large = Utilities.PhysicalPath + sFileName;
                        file.image_thumbnail = String.Format("{0}Thumbs/{1}", Utilities.PhysicalPath, sFileName);
                        changeImage = true;
                    }
                }

                UpdateModel(file);
                _ctx.SaveChanges();
                if (changeImage)
                {
                    if (!string.IsNullOrEmpty(oldImage))
                        DeleteFile(Request, Utilities.VirtualPath, oldImage);
                    if (!string.IsNullOrEmpty(oldThumbImage))
                        DeleteFile(Request, Utilities.VirtualPath + "Thumbs", oldThumbImage);
                }
                ViewData["Msg"] = "Đã cập nhật!";
                InitCategory(0);
                return View(file);
                //return RedirectToAction("Indexvideo");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Delete(int id)
        {
            try
            {
                // TODO: Add delete logic here
                //if (!IsAuthenticateAdmin())
                //    return RedirectToAction("LogOn", "DashBoard");
                var file = _ctx.multimedia_set.SingleOrDefault(p => p.set_id == id);
                if (file != null)
                {
                    _ctx.multimedia_set.DeleteObject(file);
                    _ctx.SaveChanges();
                    DeleteFile(Request, Utilities.VirtualPath, file.image_large);
                    DeleteFile(Request, Utilities.VirtualPath + "Thumbs", file.image_thumbnail);
                }
                return RedirectToAction("IndexMultimediaSet");
            }
            catch
            {
                return RedirectToAction("IndexMultimediaSet");
            }
        }
        public ActionResult Create()
        {
            InitCategory(0);
            var file = new multimedia_set();
            file.created_date = DateTime.Today;
            return View(file);
        }

        //
        // POST: /FunRingManagement/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create([Bind(Exclude = "file_id")]multimedia_set file, HttpPostedFileBase uploadFile)
        {
            // TODO: Add update logic here
            //if (!IsAuthenticateAdmin())
            //    return RedirectToAction("LogOn", "DashBoard");
            try
            {

                if (uploadFile != null)
                {
                    var fileName = Path.GetFileName(uploadFile.FileName);

                    var sFileName = GenerateFileNameByNo(Request, Utilities.VirtualPath, fileName,
                                                         DateTime.Now.ToString("yyyyMMddhhmmss"));
                    var filePath = Path.Combine(Request.MapPath(Utilities.VirtualPath), sFileName);
                    var fileThumbPath = Path.Combine(Request.MapPath(Utilities.VirtualPath + "Thumbs/"), sFileName);
                    ResizeImage(uploadFile.InputStream, fileThumbPath, 99, 99, true);
                    ResizeImage(uploadFile.InputStream, filePath, 400, 300, true);
                    file.image_large = Utilities.PhysicalPath + sFileName;
                    file.image_thumbnail = String.Format("{0}Thumbs/{1}", Utilities.PhysicalPath, sFileName);
                }

                file.created_date = DateTime.Today;
                InitCategory(0);
                _ctx.multimedia_set.AddObject(file);
                _ctx.SaveChanges();
                ViewData["Msg"] = "Đã tạo thành công!";
                return RedirectToAction("IndexMultimediaSet");
            }
            catch
            {
                InitCategory(0);
                return RedirectToAction("Create", new multimedia_set());

            }
        }

        #region --Utitlies-
        private void InitCategory(object selected)
        {
            var ctg = _ctx.categories.ToList();
            ctg.Insert(0, new category());
            ViewData["categorys"] = new SelectList(ctg.AsEnumerable(), "category_id", "name", selected);
        }
        static readonly string[] ImageExtensions = { ".PNG", ".JPG", ".JPEG", ".BMP", ".GIF" };
        static readonly string[] AudioExtensions = { ".WMA", ".MP3", ".OGG", ".RMA" };
        static readonly string[] VideoExtensions = { ".AVI", ".MP4", "FLV" };

        private FileTypes? GetFileType(string file)
        {
            var ex = Path.GetExtension(file).ToUpperInvariant();
            if (ImageExtensions.Any(x => x == ex))
            {
                return FileTypes.Image;
            }
            else if (AudioExtensions.Any(x => x == ex))
            {
                return FileTypes.Audio;
            }
            else if (VideoExtensions.Any(x => x == ex))
            {
                return FileTypes.Video;
            }
            else
            {
                return null;
            }
        }

        #endregion
    }
}
